package com.shali.wechat.order.service.impl;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.shali.wechat.order.dto.CartDTO;
import com.shali.wechat.order.entity.ProductInfo;
import com.shali.wechat.order.enums.ProductStatusEnum;
import com.shali.wechat.order.enums.ResultEnum;
import com.shali.wechat.order.exception.ProductException;
import com.shali.wechat.order.repository.ProductInfoRepository;
import com.shali.wechat.order.service.ProductService;

@Service
public class ProductServiceImpl implements ProductService{

	@Autowired
	private ProductInfoRepository productInfoRepository;
	
	@Override
	public List<ProductInfo> findUpAll() {
		return productInfoRepository.findByProductStatus(ProductStatusEnum.UP.getCode());
	}

	@Override
	public List<ProductInfo> findByIds(List<String> ids) {
		return productInfoRepository.findByProductIdIn(ids);
	}

	@Override
	@Transactional
	public void decreaseStock(List<CartDTO> cartList) {
		for(CartDTO cart:cartList) {
			Optional<ProductInfo> productInfoOptional = productInfoRepository.findById(cart.getProductId());
			//商品是否存在
			if(!productInfoOptional.isPresent()) {
				throw new ProductException(ResultEnum.PRODUCT_NOT_EXIST);
			}
			
			ProductInfo productInfo = productInfoOptional.get();
			Integer result= productInfo.getProductStock() - cart.getProductQuantity();
			//库存是否足够
			if(result < 0) {
				throw new ProductException(ResultEnum.PRODUCT_STOCK_ERROR);
			}
			
			productInfo.setProductStock(result);
			productInfoRepository.save(productInfo);
			
		}
	}

}
